<template>
  <div class="order-detail-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <h1 class="page-title">问诊单详情-{{ getStatusText(orderDetail?.status) }}</h1>
      <button class="back-btn" @click="goBack">返回</button>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <div class="loading-spinner"></div>
      <p>加载中...</p>
    </div>

    <!-- 错误状态 -->
    <div v-else-if="error" class="error-container">
      <p>{{ error }}</p>
      <button @click="loadOrderDetail" class="retry-btn">重试</button>
    </div>

    <!-- 数据内容 -->
    <div v-else-if="orderDetail" class="order-detail-content">
      <!-- 患者信息区域 -->
      <div class="info-section">
        <div class="section-header">患者信息</div>
        <div class="section-content">
          <div class="info-row">
            <div class="info-item">
              <span class="label">患者姓名：</span>
              <span class="value">{{ orderDetail.patientName || '未知' }}</span>
            </div>
            <div class="info-item">
              <span class="label">手机号：</span>
              <span class="value">{{ orderDetail.patientPhone || '未知' }}</span>
            </div>
            <div class="info-item">
              <span class="label">医院：</span>
              <span class="value">{{ orderDetail.hospitalName || '未知' }}</span>
            </div>
          </div>
          <div class="info-row">
            <div class="info-item">
              <span class="label">科室：</span>
              <span class="value">{{ orderDetail.departmentName || '未知' }}</span>
            </div>
            <div class="info-item">
              <span class="label">医生：</span>
              <span class="value">{{ orderDetail.doctorName || '未知' }}</span>
            </div>
            <div class="info-item">
              <span class="label">问诊方式：</span>
              <span class="value">{{ orderDetail.consultationTypeText || getConsultationTypeText(orderDetail.consultationType) }}</span>
            </div>
          </div>
          <div class="info-row">
            <div class="info-item">
              <span class="label">提交时间：</span>
              <span class="value">{{ formatDateTime(orderDetail.submitTime) }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 订单信息区域 -->
      <div class="info-section">
        <div class="section-header">订单信息</div>
        <div class="section-content">
          <div class="info-row">
            <div class="info-item">
              <span class="label">订单编号：</span>
              <span class="value">{{ orderDetail.orderNo || '未知' }}</span>
            </div>
            <div class="info-item">
              <span class="label">状态：</span>
              <span class="value status-tag" :class="getStatusClass(orderDetail.status)">{{ orderDetail.statusText || getStatusText(orderDetail.status) }}</span>
            </div>
            <div class="info-item">
              <span class="label">应付金额：</span>
              <span class="value amount">¥{{ formatAmount(orderDetail.fee) }}</span>
            </div>
          </div>
                     <div class="info-row">
             <div class="info-item">
               <span class="label">优惠金额：</span>
               <span class="value coupon">¥{{ formatAmount(orderDetail.discountAmount || 0) }}</span>
             </div>
             <div class="info-item">
               <span class="label">实际支付：</span>
               <span class="value actual-payment">¥{{ formatAmount(orderDetail.actualPayment || orderDetail.fee) }}</span>
             </div>
             <div class="info-item">
               <span class="label">预约时间：</span>
               <span class="value">{{ orderDetail.appointmentTime ? formatDateTime(orderDetail.appointmentTime) : '暂无' }}</span>
             </div>
           </div>
           <!-- 已退诊状态特有字段 -->
           <div v-if="orderDetail.status === 4" class="info-row">
             <div class="info-item">
               <span class="label">退诊原因：</span>
               <span class="value">{{ orderDetail.cancelReason || '不对症' }}</span>
             </div>
             <div class="info-item">
               <span class="label">退还金额：</span>
               <span class="value refund-amount">¥{{ formatAmount(orderDetail.refundAmount || orderDetail.fee) }}</span>
             </div>
           </div>
                 </div>
       </div>

       <!-- 已完成状态特有区域：接诊信息 -->
       <div v-if="orderDetail.status === 2" class="info-section">
         <div class="section-header">接诊信息</div>
         <div class="section-content">
           <div class="info-row">
             <div class="info-item">
               <span class="label">接诊时间：</span>
               <span class="value">{{ formatConsultationTime(orderDetail.consultationTime || orderDetail.appointmentTime) }}</span>
             </div>
             <div class="info-item">
               <span class="label">通话时长：</span>
               <span class="value">{{ orderDetail.callDuration || '00:16' }}</span>
             </div>
           </div>
           <div class="info-row">
             <div class="info-item">
               <span class="label">患者评分：</span>
               <span class="value">
                 <div class="star-rating">
                   <span v-for="i in 5" :key="i" class="star" :class="{ 'filled': i <= (orderDetail.rating || 5) }">★</span>
                 </div>
               </span>
             </div>
           </div>
           <div class="info-row">
             <div class="info-item full-width">
               <span class="label">患者评价：</span>
               <span class="value review-text">{{ orderDetail.review || '张医生经验丰富,医术精湛,用药精准。因为头晕看了数十位大夫都没有起色,在app上找到张主任,吃药后病情好转了' }}</span>
             </div>
           </div>
         </div>
       </div>
     </div>
   </div>
 </template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import api from '../utils/request'

const route = useRoute()
const router = useRouter()
const loading = ref(true)
const error = ref('')
const orderDetail = ref<any>(null)
const orderId = route.params.id as string

console.log('组件初始化，订单ID:', orderId)

const loadOrderDetail = async () => {
  console.log('开始加载订单详情')
  try {
    loading.value = true
    error.value = ''
    
    // 调用API获取订单详情
    const response: any = await api.consultationOrder.getDetail(parseInt(orderId))
    console.log('API响应:', response)
    
    if (response && response.code === 200 && response.data && response.data.orderInfo) {
      orderDetail.value = response.data.orderInfo
      console.log('获取到订单数据:', orderDetail.value)
      error.value = ''
    } else {
      error.value = response?.msg || '获取订单详情失败'
      console.error('API返回错误:', response)
    }
    
  } catch (err: any) {
    console.error('加载失败:', err)
    error.value = err.message || '加载失败'
  } finally {
    loading.value = false
    console.log('加载完成，loading:', loading.value, 'orderDetail:', orderDetail.value)
  }
}

const goBack = () => {
  router.back()
}

const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '未知'
  try {
    const date = new Date(dateTime)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')
    
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  } catch (e) {
    return dateTime
  }
}

const formatConsultationTime = (dateTime: string) => {
  if (!dateTime) return '未知'
  try {
    const date = new Date(dateTime)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    
    // 获取星期几
    const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
    const weekday = weekdays[date.getDay()]
    
    return `${year}-${month}-${day} ${weekday} ${hours}:${minutes}`
  } catch (e) {
    return dateTime
  }
}

const getConsultationTypeText = (type: number) => {
  switch (type) {
    case 1: return '图文问诊'
    case 2: return '视频问诊'
    case 3: return '电话问诊'
    case 4: return '极速电话'
    case 5: return '复诊开药'
    default: return '未知'
  }
}

const getStatusText = (status: number) => {
  switch (status) {
    case 0: return '待支付'
    case 1: return '进行中'
    case 2: return '已完成'
    case 3: return '已取消'
    case 4: return '已退诊'
    default: return '未知'
  }
}

const getStatusClass = (status: number) => {
  switch (status) {
    case 0: return 'pending'
    case 1: return 'in-progress'
    case 2: return 'completed'
    case 3: return 'cancelled'
    case 4: return 'refunded'
    default: return 'pending'
  }
}

const formatAmount = (amount: number) => {
  if (amount === null || amount === undefined) return '0.00'
  return amount.toFixed(2)
}

onMounted(() => {
  console.log('组件挂载完成')
  if (orderId) {
    loadOrderDetail()
  } else {
    error.value = '订单ID无效'
    loading.value = false
  }
})
</script>

<style scoped>
.order-detail-page {
  width: 100%;
  background-color: white;
  min-height: 100vh;
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background-color: white;
  border-bottom: 1px solid #e8e8e8;
}

.page-title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin: 0;
}

.back-btn {
  background-color: #1890ff;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.loading-container {
  text-align: center;
  padding: 60px;
  background: white;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #1890ff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 20px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.error-container {
  text-align: center;
  padding: 60px;
  background: white;
}

.retry-btn {
  background-color: #1890ff;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
  margin-top: 10px;
}

.order-detail-content {
  padding: 20px;
}

.info-section {
  margin-bottom: 20px;
  background: white;
  border: 1px solid #d0d0d0;
  border-radius: 4px;
  overflow: hidden;
}

.section-header {
  background-color: #f5f5f5;
  padding: 15px 20px;
  font-size: 16px;
  font-weight: bold;
  color: #333;
  border-bottom: 1px solid #d0d0d0;
  text-align: center;
}

.section-content {
  padding: 20px;
}

.info-row {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15px;
  line-height: 1.5;
}

.info-row:last-child {
  margin-bottom: 0;
}

.info-item {
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-right: 20px;
}

.info-item:last-child {
  margin-right: 0;
}

.label {
  color: #666;
  font-weight: 500;
  min-width: 80px;
  flex-shrink: 0;
  font-size: 14px;
}

.value {
  color: #333;
  text-align: right;
  flex: 1;
  margin-left: 10px;
  font-size: 14px;
}

.status-tag {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
}

.status-tag.pending {
  background-color: #faad14;
  color: white;
}

.status-tag.in-progress {
  background-color: #1890ff;
  color: white;
}

.status-tag.completed {
  background-color: #52c41a;
  color: white;
}

.status-tag.cancelled {
  background-color: #ff4d4f;
  color: white;
}

.status-tag.refunded {
  background-color: #722ed1;
  color: white;
}

.amount {
  color: #1890ff;
  font-weight: bold;
  font-size: 14px;
}

.coupon {
  color: #52c41a;
  font-weight: bold;
  font-size: 14px;
}

.actual-payment {
  color: #f5222d;
  font-weight: bold;
  font-size: 14px;
}

.refund-amount {
  color: #722ed1;
  font-weight: bold;
  font-size: 14px;
}

.star-rating {
  display: flex;
  gap: 2px;
}

.star {
  color: #ddd;
  font-size: 16px;
  cursor: default;
}

.star.filled {
  color: #faad14;
}

.review-text {
  text-align: left;
  white-space: pre-wrap;
  word-break: break-word;
  line-height: 1.6;
  color: #333;
}
</style> 